﻿Imports System.Configuration
Imports System.Windows.Threading
Imports Microsoft.Win32
Imports System.Reflection
Imports System.Windows
Imports System.Windows.Controls
Imports System.Windows.Media

Namespace Coding4Fun.PrinterDisplayHack
	''' <summary>
	''' Interaction logic for MainWindow.xaml
	''' </summary>
	Partial Public Class MainWindow
		Inherits Window

		Private _timer As DispatcherTimer
		Private _lastMessage As String = ""
		Private _logs As New Queue(Of LogEntry)()
		Private _settingsHaveChanged As Boolean = False

		Public Sub New()
			InitializeComponent()

			_timer = New DispatcherTimer With {.Interval = TimeSpan.FromMilliseconds(1000*60*5)}
			AddHandler _timer.Tick, Sub(s, a) SendTickerToPrinter()
		End Sub

		Private Sub GetPrice_Click(ByVal sender As Object, ByVal e As RoutedEventArgs)
			Dim result As String = GetStockPrice()
			LogText(rtfLog, result)
		End Sub

		Private Sub GetPrinter_Click(ByVal sender As Object, ByVal e As RoutedEventArgs)
			Dim fp As New FindPrinters()

			Dim showDialogReturn? As Boolean = fp.ShowDialog()
			Dim dlgResult As Boolean = showDialogReturn IsNot Nothing AndAlso showDialogReturn.Value

			If dlgResult Then
				PrinterHackSettings.Default.PrinterAddress = fp.SelectedIpAddress
			End If
		End Sub

		Private Sub btnExit_Click(ByVal sender As Object, ByVal e As RoutedEventArgs)
			Me.Close()
		End Sub

		Private Sub btnSave_Click(ByVal sender As Object, ByVal e As RoutedEventArgs)
			If _settingsHaveChanged Then
				_settingsHaveChanged = False

				StopPrinterHacking()

				PrinterHackSettings.Default.Save()

				StartWithWindows(PrinterHackSettings.Default.StartWithWindows)

				MessageBox.Show("Settings saved.", My.Resources.DisplayTitle, MessageBoxButton.OK, MessageBoxImage.Information)
			End If

			StartPrinterHacking()

			Me.Hide()
		End Sub

		Private Sub grid_Loaded(ByVal sender As Object, ByVal e As RoutedEventArgs)
			grid.DataContext = PrinterHackSettings.Default

			AddHandler PrinterHackSettings.Default.SettingChanging, AddressOf SettingsChanged
		End Sub

		Private Sub StartWithWindows(ByVal start As Boolean)
			Using hkcu As RegistryKey = Registry.CurrentUser
				Using runKey As RegistryKey = hkcu.OpenSubKey("Software\Microsoft\Windows\CurrentVersion\Run", True)
					If runKey Is Nothing Then
						Return
					End If

					If start Then
						runKey.SetValue(My.Resources.Code4FunStockPrinter, System.Reflection.Assembly.GetEntryAssembly().Location)
					Else
						If runKey.GetValue(My.Resources.Code4FunStockPrinter) IsNot Nothing Then
							runKey.DeleteValue(My.Resources.Code4FunStockPrinter)
						End If
					End If
				End Using
			End Using
		End Sub

		Public Function SettingsAreValid() As Boolean
			Return ((Not String.IsNullOrWhiteSpace(PrinterHackSettings.Default.PrinterAddress)) AndAlso (Not String.IsNullOrWhiteSpace(PrinterHackSettings.Default.StockSymbol)))
		End Function

		Public Sub SendTickerToPrinter()
			If SettingsAreValid() Then
				Dim message As String = GetStockPrice()

				If message.Equals(_lastMessage) Then
					LogText(rtfLog, "No change")
				Else
					Dim sendToPrinter As SendToPrinter = New SendToPrinter With {.Host = PrinterHackSettings.Default.PrinterAddress}

					sendToPrinter.Send(message)

					LogText(rtfLog, message)
					_lastMessage = message
				End If
			End If
		End Sub

		Public Sub UpdateLog(ByVal rtb As RichTextBox)
			Dim i As Integer = 0

			For Each lg As LogEntry In _logs
				i += 1
				Dim tr As New TextRange(rtb.Document.ContentEnd, rtb.Document.ContentEnd) With {.Text = String.Format("{0} : ", lg.LogTime.ToString("hh:mm:ss"))}
				tr.ApplyPropertyValue(TextElement.ForegroundProperty, Brushes.Red)

				tr = New TextRange(rtb.Document.ContentEnd, rtb.Document.ContentEnd) With {.Text = lg.LogMessage & Environment.NewLine}
				tr.ApplyPropertyValue(TextElement.ForegroundProperty, Brushes.White)
			Next lg

			If i > 10 Then
				_logs.Dequeue()
			End If

			rtb.ScrollToEnd()
		End Sub

		Public Sub LogText(ByVal message As String)
			LogText(rtfLog, message)
		End Sub

		Public Sub LogText(ByVal rtb As RichTextBox, ByVal message As String)
			_logs.Enqueue(New LogEntry() With {.LogTime = Date.Now, .LogMessage = message})

			UpdateLog(rtb)
		End Sub

		Private Function GetStockPrice() As String
			Dim tickerSymbol As String = PrinterHackSettings.Default.StockSymbol
			If Not String.IsNullOrWhiteSpace(tickerSymbol) Then
				Dim stockPrice As New StockPrice(tickerSymbol)
				Dim result As String

				Dim lastTradedPrice As String = stockPrice.GetPrice()
				Dim currentPrice As Double

				If Double.TryParse(lastTradedPrice, currentPrice) Then
					result = String.Format("{0}: {1:C}", tickerSymbol, currentPrice)
				Else
					result = String.Format("{0}: {1}", tickerSymbol, lastTradedPrice)
				End If

				Return result
			End If

			Return String.Empty
		End Function

		Public Sub StartPrinterHacking()
			If PrinterHackSettings.Default.Enabled Then
				SendTickerToPrinter()
				_timer.Start()
			End If
		End Sub

		Public Sub StopPrinterHacking()
			_timer.Stop()
		End Sub

		Private Sub SettingsChanged(ByVal sender As Object, ByVal e As SettingChangingEventArgs)
			_settingsHaveChanged = True
		End Sub
	End Class
End Namespace
